from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt

from app01.utils.form import BootstrapModelForm
from app01.models import Task


from app01.utils.pagination import Pagination

class TaskModelForm(BootstrapModelForm):
    class Meta:
        model = Task
        fields = "__all__"


@csrf_exempt
def task_list(request):
    """ 任务列表 """

    form = TaskModelForm()

    ##########################################################
    # >>>>>生成页码与搜索
    data_dict = {}
    search_data = request.GET.get('query', "")
    # title__ccontains 表示使用title作为搜索字段进行内容匹配
    if search_data:
        data_dict["title__contains"] = search_data

        # 对搜索内容进行查询,为空表示获取所有数据
    queryset = Task.objects.filter(**data_dict).order_by('-id')

    page_object = Pagination(request, queryset, page_size=10, page_param="page")
    page_queryset = page_object.page_queryset

    # 调用对象的html方法,生成页码
    page_object.html()
    page_string = page_object.page_string

    ##########################################################
    context = {
        "queryset": page_queryset,
        "form": form,
        "page_string": page_string,
        "search_data": search_data,
    }

    return render(request, "task_list.html", context)


from app01 import models
@receiver(pre_save, sender=models.Task)
def update_id(sender, instance, **kwargs):
    if instance.id is None:
        last_id = models.Task.objects.all().order_by('-id').first().id
        instance.id = last_id + 1 if last_id else 1
def task_add(request):
    """添加"""

    if request.method == "GET":
        form=TaskModelForm()
        return render(request, "task_list.html",{"form":form})

    #数据效验
    form=TaskModelForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect("/task/list")

    return render(request, "task_list.html", {"form": form})